package be.kuleuven.thesis.framework;

import java.util.HashSet;
import java.util.Set;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import be.kuleuven.thesis.databases.LastFmManager;
import be.kuleuven.thesis.widget.DrawableManager;

public class Album {
	private Song song;
	private String artist;
	private String name;
	private String smallImageUrl;
	private String largeImageUrl;
	private Drawable image;
	private Set<AlbumListener> listeners = new HashSet<AlbumListener>();
	
	public Album(Song song) {
		this.song = song;
		song.setAlbum(this);
		this.name = "";
		this.smallImageUrl = "";
		this.largeImageUrl = "";
	}

	public Song getSong() {
		return song;
	}

	public void setSong(Song song) {
		this.song = song;
	}

	public String getArtist() {
		return artist;
	}

	public void setArtist(String artist) {
		this.artist = artist;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSmallImageUrl() {
		return smallImageUrl;
	}

	public void setSmallImageUrl(String imageUrl) {
		this.smallImageUrl = imageUrl;
	}

	public String getLargeImageUrl() {
		return largeImageUrl;
	}

	public void setLargeImageUrl(String largeImageUrl) {
		this.largeImageUrl = largeImageUrl;
	}

	public Drawable getImage() {
		return image;
	}

	public void setImage(Drawable image) {
		this.image = image;
	}
	
	public void setMetaDataInThread() {
		if(song == null)
			return;
		new SetMetaDataTask().execute();
	}
	
	private class SetMetaDataTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... arg0) {
			LastFmManager.getInstance().fetchAlbumMetaData(Album.this);
			return null;
		}
		
		@Override
		protected void onPostExecute(final Void unused) {
			for(AlbumListener listener: listeners) {
				listener.onMetaDataSet(Album.this);
				listeners.remove(this);
			}
		}
	}
	
	public void setAlbumCoverInThread() {
		if(getLargeImageUrl() == null || getLargeImageUrl().equals("not found"))
			return;
		new SetAlbumCoverTask().execute();
	}
	
	private class SetAlbumCoverTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... arg0) {
			DrawableManager dm = new DrawableManager();
			setImage(dm.fetchDrawable(getLargeImageUrl()));
			return null;
		}
		
		@Override
		protected void onPostExecute(final Void unused) {
			for(AlbumListener listener: listeners) {
				listener.onAlbumCoverSet();
				listeners.remove(Album.this);
			}
		}
	}
	
	public void registerListener(AlbumListener listener) {
		listeners.add(listener);
	}
	
	public void unRegisterListener(AlbumListener listener) {
		listeners.remove(listener);
	}
}
